import 'package:dio/dio.dart';
import 'package:logger/logger.dart';

class BaseService {
  static final Logger _logger = Logger(
      printer: PrettyPrinter(
    methodCount: 0,
    errorMethodCount: 5,
    colors: true,
    printEmojis: true,
  ));

  Logger get logger =>_logger;

  /// 记录网络请求日志
  void logRequest(RequestOptions options) {
    _logger.i('🌐 [${options.method}] => ${options.uri}');
  }

  /// 记录网络响应日志
  void logResponse(Response response) {
    _logger.i('✅ [${response.statusCode}] <= ${response.requestOptions.uri}');
  }

  /// 记录网络错误日志
  void logError(DioException e) {
    _logger.e('❌ [${e.type}] ${e.message}\n${e.stackTrace}');
  }

  /// 统一处理 Dio 异常
  String handleDioError(DioException e) {
    logError(e); //记录错误日志

    if (e.response != null) {
      final statusCode = e.response!.statusCode;
      final statusMessage = e.response!.statusMessage;
      if (statusCode == 401) {
        return '认证失败，请重新登录';
      } else if (statusCode == 403) {
        return '权限不足，无法访问';
      } else if (statusCode == 404) {
        return '请求的资源不存在';
      } else if (statusCode == 429) {
        return '请求过于频繁，请稍后再试';
      } else if (statusCode! >= 500) {
        return '服务器错误 ($statusCode)';
      }

      return '服务器错误: $statusCode - ${statusMessage ?? '未知错误'}';
    } else {
      switch (e.type) {
        case DioExceptionType.connectionTimeout:
          return '连接超时，请检查网络';
        case DioExceptionType.sendTimeout:
          return '发送数据超时';
        case DioExceptionType.receiveTimeout:
          return '接收数据超时';
        case DioExceptionType.badCertificate:
          return '证书验证失败';
        case DioExceptionType.cancel:
          return '请求已取消';
        case DioExceptionType.connectionError:
          return '网络连接失败';
        case DioExceptionType.unknown:
          return '未知网络错误: ${e.message}';
        default:
          return '网络错误: ${e.message}';
      }
    }
  }

/// 提取响应数据
  T extractData<T>(Response response, T Function(dynamic) fromJson) {
    // 允许 200 OK 和 201 Created 状态码
    if (response.statusCode != 200 && response.statusCode != 201) {
      throw '请求失败: ${response.statusCode}';
    }

    final data = response.data;

    if(response.statusCode == 201){
      return fromJson(data['data'] ?? data);  // 兼容无data字段的情况
    }

    // 处理统一响应格式 {code: 0, message: "success", data: {}}
    if (data is Map<String, dynamic>) {
      if (data['code'] != 0) {  // 假设0表示成功
        throw data['message'] ?? '请求失败';
      }
      return fromJson(data['data'] ?? data);  // 兼容无data字段的情况
    }

    // 直接解析非结构化响应
    return fromJson(data);
  }


}
/// 提取分页响应数据
PaginatedResponse<T> extractPaginatedData<T>(
    Response response,
    T Function(dynamic) fromJson,
    ) {
  final statusCode = response.statusCode ?? 0;

  // 检查HTTP状态码
  if (statusCode < 200 || statusCode >= 300) {
    throw '请求失败: $statusCode ${response.statusMessage}';
  }

  final data = response.data;

  // 处理空响应
  if (data == null) {
    throw '服务器返回空响应';
  }

  // 分页数据结构
  if (data is Map<String, dynamic>) {
    final items = data['items'] as List?;
    final total = data['total'] as int?;
    final page = data['page'] as int?;
    final limit = data['limit'] as int?;

    if (items == null) {
      throw '响应数据格式错误: 缺少 items 字段';
    }

    return PaginatedResponse<T>(
      items: items.map((e) => fromJson(e)).toList(),
      total: total ?? 0,
      page: page ?? 1,
      limit: limit ?? 10,
    );
  }

  // 默认处理
  return PaginatedResponse<T>(
    items: (data as List).map((e) => fromJson(e)).toList(),
    total: data.length,
    page: 1,
    limit: data.length,
  );
}

/// 分页响应模型
class PaginatedResponse<T> {
  final List<T> items;
  final int total;
  final int page;
  final int limit;

  PaginatedResponse({
    required this.items,
    required this.total,
    required this.page,
    required this.limit,
  });

  bool get hasMore => page * limit < total;
}